<!DOCTYPE html
        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<textarea id="code">
    var Test = function(){//aaaa for;bbb for;;;;
    this.name = 'xling';var version = '1.0';//for(i=0;i<2;i++)\n

    var str = 'for(i=0;i<10;i++){'
    str = 'while(true) bb();'

    if(true)
    bb()
    this.doSomething = function(){
    alert('here');
    for(i=0;i<10;i++){/*for;*/
    aa();
    }
    }
    } ;
    var aa = {};
    aa
    bb
</textarea>
<input type="button" value="格式" onclick="geshi()"/>

<div id="highlight"></div>
<script type="text/javascript">
    String.prototype.trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }
    String.prototype.repeat = function(time) {
        if (time <= 0) return '';
        return (new Array(time + 1)).join(this);
    }

        var queue = {
            '{':0,
            '//':0,
            '/*':0,
            '(':0,
            '"':0,
            "'":0
        };

        var queue2 = {
            '}':    '{',
            '//':   '//',
            '*/':   '/*',
            ')':    '(',
            '"':    '"',
            "'":    "'"
        }    

    var geshi = function() {

        var mutiReplace = function(){
            //alert(arguments[1]);
            switch(arguments[1]){
                case '{':
                case '(':
                case '/*':
                    if(!(queue['"'] || queue["'"] || queue['//'] || queue['/*'] )){
                        queue[arguments[1]] ++;
                        return arguments[1] == '{' || arguments[1] == '/*' ? arguments[1] + '\n' : null;
                    }
                    break;
                case '}':
                case ')':
                case '*/':
                    if(!(queue['"'] || queue["'"] || queue['//'] || queue['/*'] )){
                        queue[queue2[arguments[1]]] --;

                        return arguments[1] == '}' || arguments[1] == '*/' ? '\n' + arguments[1] + '\n' : null;
                    }
                    break;
                case '"':
                case "'":
                case '//':
                case '/*':
                    if(!(queue['"'] || queue["'"] || queue['//'] || queue['/*'] )){
                        
                    }
                    break;
            }
            
            return arguments[1];
        }

        var source = document.getElementById('code').value.trim();
        source = source.replace(/({|}|;|\/\/|\/\*|\*\/|\(|\))/g,mutiReplace);
        alert(source);
        //document.getElementById('highlight').innerHTML = '<div>' + goal.join('</div><div>') + '</div>';
    }
</script>
</body>
</html>